package com.ysd.shopcar.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONArray;
import com.ysd.shopcar.common.JSONResult;
import com.ysd.shopcar.entity.CarProdcut;
import com.ysd.shopcar.entity.CheckProductResult;
import com.ysd.shopcar.entity.ItemKill;
import com.ysd.shopcar.entity.Rule;
import com.ysd.shopcar.feign.OrderFeginClient;
import com.ysd.shopcar.feign.ProductFeginClient;
import com.ysd.shopcar.mapper.CartMapper;
import com.ysd.shopcar.param.in.AddProductToCarRequestType;
import com.ysd.shopcar.param.in.ChangeProductNumRequestType;
import com.ysd.shopcar.param.in.CheckProduct;
import com.ysd.shopcar.param.in.ProductOrderInfo;
import com.ysd.shopcar.param.in.SubmitOrderRequestType;
import com.ysd.shopcar.param.out.CarProdcutListResponseType;
import com.ysd.shopcar.param.out.SubmitOrderResponseType;
import com.ysd.shopcar.service.ShopCarService;
import com.ysd.shopcar.utils.JsonUtils;
import com.ysd.shopcar.utils.StringUtil;

@Service
@Transactional(readOnly = false)
public class ShopCarServiceImpl implements ShopCarService {
	
	@Autowired
	private CartMapper cartMapper;
	
	@Autowired
	private ProductFeginClient productFeginClient;
	
	@Autowired
	private OrderFeginClient orderFeginClient;
	
//    @Autowired
//    private RedissonClient redissonClient;

	@Override
	public JSONResult<ChangeProductNumRequestType> changeProductNumByUIDAndPID(ChangeProductNumRequestType request) {
		@SuppressWarnings("unchecked")
		JSONResult<ChangeProductNumRequestType> result = JSONResult.build(HttpStatus.SC_OK, "success", request);
		int num = 0;
		try {
        	//判断用户传的operation 操作 1：添加  2：减少 3：删除
        	if("1".equals(request.getOperation())) {
        		//添加商品
        		//根据用户ID和产品ID查询购物车中的商品数量
        		//int productNums = ProductFeginClientCallBack.
        		//调用添加购物车商品数量方法
        		num = cartMapper.addProductNum(request);
        		if(!(num > 0)) {
        			result.setMsg("添加数量失败！");
        			result.setStatus(-1);
        		}
        	}else if("2".equals(request.getOperation())) {
        		//减少商品
        		//调用减少购物车商品数量方法
        		num = cartMapper.subProductNum(request);
        		if(!(num > 0)) {
        			result.setMsg("减少数量失败！");
        			result.setStatus(-1);
        		}
        	}else if("3".equals(request.getOperation())) {
        		//删除商品
        		//调用删除购物车商品的方法
        		num = cartMapper.delProduct(request);
        		if(!(num > 0)) {
        			result.setMsg("删除商品失败！");
        			result.setStatus(-1);
        		}
        	}else {
            	result.setStatus(-1);
            	result.setMsg("非法参数-operation");
        	}
            
        } catch (Exception e) {
        	ChangeProductNumRequestType changeProductNumRequestType = new ChangeProductNumRequestType();
        	result.setStatus(-1);
        	result.setMsg("接口异常");
            result.setData(changeProductNumRequestType);
            return result;
        }
        return result;
	}

	@Override
	public JSONResult<CarProdcutListResponseType> getCatProductsByUID(Long uid) {
		@SuppressWarnings("unchecked")
		JSONResult<CarProdcutListResponseType> result = JSONResult.build(HttpStatus.SC_OK, "success", null);
		
		try {
			CarProdcutListResponseType carProdcutListResponseType = new CarProdcutListResponseType();
			List<CarProdcut> productList = cartMapper.queryCPListByUID(uid);
			//计算商品信息是否已经失效
			List<CheckProductResult> prList = checkProductInfo(productList);
			if(prList.size() > 0) {//验价没有通过
				for(CheckProductResult pr : prList) {
					productList.stream().forEach(cp ->{
						if(pr.getId() == cp.getFPid() && !pr.isSuccess()) {//验证失败了
							cp.setColor(pr.getMessage());
						}
					});
				}
			}
			//计算活动商品优惠价
			calSpecialPrice(productList);
			carProdcutListResponseType.setProductList(productList);
			//计算金额和运费
			calPriceAndFreight(carProdcutListResponseType);
			result.setData(carProdcutListResponseType);
		} catch (Exception e) {
			CarProdcutListResponseType carProdcutListResponseType = new CarProdcutListResponseType();
        	result.setStatus(-1);
        	result.setMsg("接口异常");
            result.setData(carProdcutListResponseType);
            e.printStackTrace();
		}
		return result;
	}

	//计算活动商品优惠价
	private void calSpecialPrice(List<CarProdcut> productList) {
		productList.stream().forEach(p -> {
			p.setSpecialPrice(getSpecialPrice(p));
		});
	}
	
	//获取商品优惠价
	private String getSpecialPrice(CarProdcut p) {
		if(StringUtil.isNotNullOrEmpty(p.getRule())) {
			String str = p.getRule().replace("/", "");
			Rule rule = JSONArray.parseObject(str, Rule.class);
			if(rule.getActiveType() == 1) {//满额减
				//计算满减次数
				int mjTimes = new BigDecimal(p.getPrice()).multiply(new BigDecimal(p.getNum())).divide(new BigDecimal(rule.getLevelMoney()),0 , BigDecimal.ROUND_DOWN).intValue();
				return new BigDecimal(p.getPrice()).multiply(new BigDecimal(p.getNum())).subtract(new BigDecimal(rule.getSubtractMoney()).multiply(new BigDecimal(mjTimes))).toString();
			}else if(rule.getActiveType() == 2) {//满件折
				if(p.getNum() >= rule.getLevelNum()) {//购买数量超过折扣标准数量
					return new BigDecimal(p.getPrice()).multiply(new BigDecimal(rule.getDiscount())).divide(new BigDecimal(10),0 , BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(p.getNum())).toString();
				}
			}
		}
		return null;
	}

	//计算金额和运费
	private void calPriceAndFreight(CarProdcutListResponseType carProdcutListResponseType) {
		if(StringUtil.isNotNullOrZeroElem(carProdcutListResponseType.getProductList())) {
			//设置商品项个数f
			carProdcutListResponseType.setProductItems(carProdcutListResponseType.getProductList().size());
			
			BigDecimal freight = new BigDecimal(0);//运费
			
//			carProdcutListResponseType.getProductList().stream().forEach(p ->{
//				freight.add(new BigDecimal(1));
//				p.setMoney(new BigDecimal(p.getPrice()).multiply(new BigDecimal(p.getNum())).setScale(2,BigDecimal.ROUND_HALF_DOWN).toString());
//				subtotal.add(new BigDecimal(p.getMoney()));
//			});
			BigDecimal subtotal = carProdcutListResponseType.getProductList().stream().map(item->new BigDecimal(item.getPrice()).multiply(new BigDecimal(item.getNum()))).reduce(BigDecimal.ZERO,BigDecimal::add);
			
			carProdcutListResponseType.setFreight(freight.setScale(2,BigDecimal.ROUND_HALF_DOWN).toString());
			carProdcutListResponseType.setSubtotal(subtotal.setScale(2,BigDecimal.ROUND_HALF_DOWN).toString());
			carProdcutListResponseType.setTotal(subtotal.add(freight).toString());
		}
	}

	/**
	 * 将产品信息插入购物车
	 */
	@Override
	public JSONResult<Object> addProductToShopCar(AddProductToCarRequestType request) {
		@SuppressWarnings("unchecked")
		JSONResult<Object> result = JSONResult.build(HttpStatus.SC_OK, "success", null);
		try {
			//根据用户ID与产品ID查询该用户购物车中是否已经存在该商品
			if(cartMapper.existencePro(request.getPid(),request.getUid()) > 0) {
				//调用加1的方法
				ChangeProductNumRequestType p = new ChangeProductNumRequestType();
				p.setUid(request.getUid());
				p.setPid(request.getPid());
				int num = cartMapper.addProductNum(p);
				if(num == 0) {
					result.setMsg("添加购物车失败！");
					result.setStatus(-1);
				}
			}else {
				int num = cartMapper.addProductToShopCar(request);
				if(num == 0) {
					result.setMsg("添加购物车失败！");
					result.setStatus(-1);
				}
			}
			
		} catch (Exception e) {
			result.setMsg("接口异常！");
			result.setStatus(-1);
		}
		return result;
	}

	//?str=[{id:1,newprice:169,ext1:2},{id:2,newprice:149,ext1:2}]
	@Override
	public JSONResult<SubmitOrderResponseType> submitOrder(SubmitOrderRequestType request) {
		JSONResult<SubmitOrderResponseType> result = JSONResult.build(200, "订单提交成功", null);
		try {
			//根据用户ID查询该用户得购物车信息
			List<CarProdcut> carProList = cartMapper.queryCPListByUID(Long.parseLong(request.getUid()));
			
			//计算购物车中商品得总数量
			int countNum = carProList.stream().mapToInt(CarProdcut::getNum).sum();
			
			//计算商品信息是否已经失效
			List<CheckProductResult> prList = checkProductInfo(carProList);
			//产品验存验价结果List
			List<ProductOrderInfo> errorList = new ArrayList<>();
			//验证产品信息是否有效
			for(CheckProductResult pr : prList) {
				carProList.stream().forEach(cp ->{
					if(pr.getId() == cp.getFPid() && !pr.isSuccess()) {//验证失败了
						ProductOrderInfo poi = JsonUtils.copyObject(cp, ProductOrderInfo.class);
						poi.setErrorCode(-1);
						poi.setErrorMag(pr.getMessage());
						errorList.add(poi);
					}
				});
			}
			
			if(errorList.size() > 0) {//验价没有通过
				SubmitOrderResponseType st = new SubmitOrderResponseType();
				st.setPoList(errorList);
				result.setData(st);
				result.setStatus(-2);
				result.setMsg("验价失败");
			}else {
				//验存验价通过之后在提交订单
				Map<String,String> orders = new HashMap<>();
				orders.put("fUid", request.getUid());//用户ID
				orders.put("money", request.getTotal());//订单应支付金额
				orders.put("num", countNum+"");//商品总数
				orders.put("ext1", JsonUtils.toJSONString(carProList));//订单明细
				
				boolean flag = orderFeginClient.subOrders(orders);
				if(flag) {
					//提交订单成功，则删除购物车中得数据
					int delResult = cartMapper.delCarProduct(request.getUid());
				}else {
					//提交订单失败
					result.setStatus(-1);
					result.setMsg("订单提交失败！");
				}
			}
		} catch (Exception e) {
			result.setStatus(-1);
			result.setMsg("接口异常！");
		}
		return result;
	}

	private List<CheckProductResult> checkProductInfo(List<CarProdcut> carProList) {
		//调用产品中心验价接口
		List<CheckProduct> checkProList = new ArrayList<>();
		carProList.stream().forEach(pro ->{
			CheckProduct p = new CheckProduct();
			p.setId(pro.getFPid().toString());
			p.setNewprice(pro.getPrice());
			p.setExt1(pro.getNum()+"");
			checkProList.add(p);
		});
		Map<String,Object> maps = productFeginClient.checkProduct(JsonUtils.toJSONString(checkProList));
		List<CheckProductResult> prList = new ArrayList<CheckProductResult>();
		if(maps != null) {
			for(Object obj : maps.values()) {
				prList.add(JsonUtils.copyObject(obj, CheckProductResult.class));
			}
		}
		return prList;
	}

	@Override
	public JSONResult submitMsOrder(AddProductToCarRequestType request) {
		
		JSONResult result = JSONResult.build(200, "秒杀成功，请及时付款！", null);
        final String lockKey = new StringBuffer().append(request.getPid()).append("p-u").append(request.getUid()).append("-RedissonLock").toString();
        // 唯一的key获得锁
        //RLock lock = redissonClient.getLock(lockKey);
        try {
            // 人性化时间，可重入，30s尝试，获取锁后10s释放
          //  Boolean cacheRes = lock.tryLock(30, 10, TimeUnit.SECONDS);
            //if (cacheRes) {
                // 核心业务逻辑的处理
               // if (itemKillSuccessMapper.countByKillUserId(request.getPid(), request.getUid()) <= 0) {//判断改用户是否已经下单了
                    ItemKill itemKill = cartMapper.selectByPId(request.getPid());
                    if (itemKill != null && 1 == itemKill.getCanKill() && itemKill.getNum() > 0) {
                    	//抢购商品数量减1
                        int res = cartMapper.updateMSProdcut(request.getPid());
                        if (res > 0) {
                            //下单
                        	Map<String,String> orders = new HashMap<>();
            				orders.put("fUid", request.getUid());//用户ID
            				orders.put("money", new BigDecimal(request.getPrice()).multiply(new BigDecimal(request.getNum())).toString() );//订单应支付金额
            				orders.put("num", request.getNum()+"");//商品总数
            				List<CarProdcut> carProList = new ArrayList<>();
            				CarProdcut carProduct = JsonUtils.copyObject(request, CarProdcut.class);
            				carProduct.setFUid(Integer.parseInt(request.getUid()));
            				carProduct.setFPid(Integer.parseInt(request.getPid()));
            				carProduct.setSpecialPrice(request.getPrice());
            				carProList.add(carProduct);
            				orders.put("ext1", JsonUtils.toJSONString(carProList));//订单明细
            				boolean flag = orderFeginClient.subOrders(orders);
                            if(flag) {
                            	//秒杀成功
                            	return result;
                            }else {
                            	result.setStatus(-1);
                            	result.setMsg("秒杀失败！");
                            	//秒杀失败
                            }
                        }else {
                        	result.setStatus(-1);
                        	result.setMsg("库存不足！");
                        }
                    }else {
                    	result.setStatus(-1);
                    	result.setMsg("库存不足！");
                    }
//                } else {
//                    throw new Exception("redisson-您已经抢购过该商品了!");
//                }
           // }
        } catch (Exception e) {
			e.printStackTrace();
		} finally {
           // lock.unlock();
            // 强制释放
            //lock.forceUnlock();
        }
        return result;
	}

	private CarProdcut copyBean(AddProductToCarRequestType request) {
		CarProdcut carProdcut = new CarProdcut();
		carProdcut.setFUid(Integer.parseInt(request.getUid()));
		carProdcut.setFPid(Integer.parseInt(request.getPid()));
		return carProdcut;
	}

}
